package com.tomato.wangzh.grpc.server;

import com.tomato.wangzh.grpc.common.HelloRequest;
import com.tomato.wangzh.grpc.common.HelloResponse;
import com.tomato.wangzh.grpc.common.HelloServiceGrpc;
import io.grpc.Context;
import io.grpc.Status;
import io.grpc.stub.StreamObserver;

import java.util.UUID;
import java.util.logging.Logger;

// Grpc 必须继承 HelloServiceImplBase
public class GrpcService extends HelloServiceGrpc.HelloServiceImplBase {

    private Logger logger  = Logger.getLogger(GrpcService.class.getName());

    /**
     * gprc远程调用 需要重写该方法，这个方法是在 proto文件里面定义的
     * @param request 数据请求
     * @param responseObserver 响应
     */
    @Override
    public void hellRpcTest(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
        try {
            // 获取请求参数
            String param = request.getParam();

            UUID uuid = UUID.randomUUID();
            // 创建响应对象
            HelloResponse response = HelloResponse.newBuilder().setResult(param + uuid.toString()).build();

            Thread.sleep(60000);

            // 如果当前客户端取消连接
            if (Context.current().isCancelled()) {
                logger.info("request is cancelled");
                responseObserver.onError(Status.CANCELLED.withDescription("request is cancelled").asRuntimeException());
                return;
            }

            // 设置响应对象
            responseObserver.onNext(response);

            // 告诉客户端处理完成
            responseObserver.onCompleted();
        } catch (Exception e) {
            e.printStackTrace();

            // 异常处理
            responseObserver.onError(Status.DATA_LOSS.withDescription(e.getMessage()).asException());
        }
    }
}
